import React, { useState, useEffect } from 'react';
import './progress_bar.css';

const TabSwitcher = () => {
  const [activeTab, setActiveTab] = useState(0); // 当前激活的标签索引
  const [progress, setProgress] = useState(new Array(9).fill(0)); // 进度条的进度数组
  const [timer, setTimer] = useState(null); // 定时器ID

  const tabs = [
    { title: '创意供给', image: 'url_to_image_1.jpg' },
    { title: '内容生产', image: 'url_to_image_2.jpg' },
    { title: '资产管理', image: 'url_to_image_3.jpg' },
    { title: '营销应用', image: 'url_to_image_4.jpg' },
    { title: '效果监测', image: 'url_to_image_5.jpg' },
    { title: '系统定制', image: 'url_to_image_6.jpg' },
    { title: '数据洞察', image: 'url_to_image_7.jpg' },
    { title: '用户体验', image: 'url_to_image_8.jpg' },
    { title: '品牌传播', image: 'url_to_image_9.jpg' }
  ];

  const intervalTime = 5000; // 进度条总时间，5秒
  const stepTime = 100; // 进度条每次更新的时间间隔，100毫秒

  const handleTabClick = (index) => {
    if (index !== activeTab) {
      setActiveTab(index);
      resetProgress();
      startProgress(index);
    }
  };

  const startProgress = (index) => {
    const newTimer = setInterval(() => {
      setProgress(prevProgress => {
        const newProgress = [...prevProgress];
        if (newProgress[index] < 100) {
          newProgress[index] += (stepTime / intervalTime * 100);
          return newProgress;
        } else {
          clearInterval(newTimer);
          setTimeout(() => {
            const nextIndex = (index + 1) % tabs.length;
            setActiveTab(nextIndex);
            startProgress(nextIndex);
          }, 1000); // 延迟1秒后切换到下一个标签
          return prevProgress;
        }
      });
    }, stepTime);

    setTimer(newTimer);
  };

  const resetProgress = () => {
    clearInterval(timer);
    setProgress(new Array(9).fill(0));
  };

  useEffect(() => {
    startProgress(activeTab);

    return () => {
      clearInterval(timer);
    };
  }, [activeTab]);

  return (
    <div className='progress_bar'>
      <div className='title'>
        <h1>一站式服务</h1>
        <h1>搭建企业视觉内容新基建</h1>
      </div>

      <div className='tab-container'>
        {tabs.map((tab, index) => (
          <div key={index} className='tab'>
            <div
              className={`tab-title ${activeTab === index ? 'active' : ''}`}
              onClick={() => handleTabClick(index)}
            >
              {tab.title}
            </div>
            <div className='progress-container'>
              <div className={`progress-bar ${activeTab === index ? 'active' : ''}`} style={{ width: `${progress[index]}%` }}></div>
            </div>
          </div>
        ))}
      </div>

      <div className='carousel'>
        <img src={tabs[activeTab].image} alt={tabs[activeTab].title} />
      </div>
    </div>
  );
};

export default TabSwitcher;